import api from '../../mock/index.js'
import { getIndexList } from '../../api/index.js'
	
const store = {
	state: {
		list: [], // 列表
		page: 1, // 从第一页开始请求
		isEnd: false // 是否到底
	},
	
	mutations: {
		updateList(state, list) {
			state.list = list
		},
		
		updatePage(state, page) {
			state.page = page
		},
		
		updateIsEnd(state, isEnd) {
			state.isEnd = isEnd
		}
	},
	
	actions: {
		// 刷新
		reload({ dispatch, commit }) {
			commit('updatePage', 1)
			commit('updateList', [])
			commit('updateIsEnd', false)
			dispatch('getNextPageList')
		},
		
		// 请求下一页
		async getNextPageList({ commit, state }, param = {}) {
			let list = state.list
			param.page = state.page
			
			// 没有下一页就不在请求
			if (state.isEnd) {
				return false
			}
			
			let res = await api.post(getIndexList, param)
			if (res.data.length) {
				list = list.concat(res.data)
				commit('updatePage', state.page + 1)
			}
			commit('updateList', list)
			commit('updateIsEnd', res.data.length <= 0)
		}
	},
	namespaced: true
}

export default store
